package com.wn.icloud.provider.uac.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wn.icloud.common.msg.ObjectRestCode;
import com.wn.icloud.common.msg.ObjectRestResponse;
import com.wn.icloud.common.utils.EnterpriseGroup;
import com.wn.icloud.common.utils.EnterpriseType;
import com.wn.icloud.common.utils.UUIDUtil;
import com.wn.icloud.common.utils.random.RandomStr;
import com.wn.icloud.provider.uac.constant.LingXiApiUrlConstant;
import com.wn.icloud.provider.uac.entity.*;
import com.wn.icloud.provider.uac.controller.lx.LingXiController;
import com.wn.icloud.provider.uac.mapper.*;
import com.wn.icloud.provider.uac.service.EnterpriseInfoService;
import com.wn.icloud.provider.uac.service.UserBiz;
import com.wn.icloud.provider.uac.service.convert.DemoBusinessConvert;
import com.wn.icloud.provider.uac.service.convert.DemoQualificationCertificateConvert;
import com.wn.icloud.provider.uac.service.convert.EnterpriseInfoConvert;
import com.wn.icloud.provider.uac.service.dto.DemoBusinessDTO;
import com.wn.icloud.provider.uac.service.dto.DemoQualificationCertificateDTO;
import com.wn.icloud.provider.uac.service.dto.EnterpriseInfo.EnterpriseData;
import com.wn.icloud.provider.uac.service.dto.EnterpriseInfo.EnterpriseId;
import com.wn.icloud.provider.uac.service.dto.EnterpriseInfo.InnovativeInformationData;
import com.wn.icloud.provider.uac.service.dto.EnterpriseInfo.LxInnovativeInformationData;
import com.wn.icloud.provider.uac.service.dto.EnterpriseInfoDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业信息表(EnterpriseInfo)表服务实现类
 *
 * @author makejava
 * @since 2020-04-24 22:23:02
 */
@Service("enterpriseInfoService")
public class EnterpriseInfoServiceImpl implements EnterpriseInfoService {
    @Resource
    private EnterpriseInfoDao enterpriseInfoDao;

    @Resource
    private EnterpriseHistoryYearInfoDao enterpriseHistoryYearInfoDao;

    @Resource
    private InnovativeInformationDao innovativeInformationDao;

    @Resource
    private DemoBusinessDao demoBusinessDao;

    @Resource
    private DemoBusinessConvert demoBusinessConvert;

    @Resource
    private DemoQualificationCertificateConvert demoQualificationCertificateConvert;

    @Resource
    private DemoQualificationCertificateDao demoQualificationCertificateDao;

    @Resource
    private EnterpriseInfoConvert enterpriseInfoConvert;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserBiz userBiz;

    @Resource
    private LinkUserEnterpriseDao linkUserEnterpriseDao;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ObjectRestResponse queryById(String id) {
        EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryById(id);
        if(null == enterpriseInfo){
            return ObjectRestResponse.failure(ObjectRestCode.NOT_FOUND_ENTERPRISE_INFO_ERROR);
        }
        String qrCode = enterpriseInfo.getQrCode();
        String random = RandomStr.randomStr(6);
        enterpriseInfo.setQrCode(qrCode+random);
        System.out.println("---"+enterpriseInfo.getPhone());
        System.out.println("------"+enterpriseInfo);
        return ObjectRestResponse.success(enterpriseInfoConvert.toDto(enterpriseInfo));
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<EnterpriseInfo> queryAllByLimit(int offset, int limit) {
        return this.enterpriseInfoDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param enterpriseInfo 实例对象
     * @return 实例对象
     */
    @Override
    public EnterpriseInfo insert(EnterpriseInfo enterpriseInfo) {
        this.enterpriseInfoDao.insert(enterpriseInfo);
        return enterpriseInfo;
    }

    /**
     * 修改数据
     *
     * @param enterpriseInfo 实例对象
     * @return 实例对象
     */
    @Override
    public ObjectRestResponse update(EnterpriseInfo enterpriseInfo) {
        this.enterpriseInfoDao.update(enterpriseInfo);
        return this.queryById(enterpriseInfo.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.enterpriseInfoDao.deleteById(id) > 0;
    }

    /**
     * 企业注册
     * @param enterpriseInfoDTO
     * @return
     */
    @Override
    @Transactional
    public ObjectRestResponse companyRegister(EnterpriseInfoDTO enterpriseInfoDTO, String userId) {

//        校验企业信息
        if (!checkEnterprise(enterpriseInfoDTO)){
            return ObjectRestResponse.failure(ObjectRestCode.ENTERPRISE_CERT_ERROR);
        }


        //企业注册主表信息
        EnterpriseInfo enterpriseInfo = enterpriseInfoConvert.toEntity(enterpriseInfoDTO);
        String uuid = UUIDUtil.getUUID();
        enterpriseInfo.setId(uuid);
        enterpriseInfo.setQrCode(UUIDUtil.getUUID());
        int i = enterpriseInfoDao.insert(enterpriseInfo);
        if(i != 1){
            return ObjectRestResponse.failure(ObjectRestCode.SAVE_ENTERPRISE_INFO_ERROR);
        }
        //企业注册主子表1信息
        List<EnterpriseHistoryYearInfo> enterpriseHistoryYearInfoList = new ArrayList<>();
         //收入
        encapsulation(enterpriseHistoryYearInfoList, enterpriseInfoDTO.getIncome(), uuid, EnterpriseGroup.MANAGE.getCode(), EnterpriseType.INCOME.getCode());
        //利润
        encapsulation(enterpriseHistoryYearInfoList, enterpriseInfoDTO.getProfit(), uuid, EnterpriseGroup.MANAGE.code(), EnterpriseType.PROFIT.code());
        //总额
        encapsulation(enterpriseHistoryYearInfoList, enterpriseInfoDTO.getTotalTax(), uuid, EnterpriseGroup.MANAGE.code(), EnterpriseType.TOTALTAX.code());
        //负债率
        encapsulation(enterpriseHistoryYearInfoList, enterpriseInfoDTO.getAssetLiabilityRatio(), uuid, EnterpriseGroup.MANAGE.code(), EnterpriseType.ASSETLIABILITYRATIO.code());
        //社保缴纳额度
        encapsulation(enterpriseHistoryYearInfoList, enterpriseInfoDTO.getSocialSecurityPaymentAmount(), uuid, EnterpriseGroup.SOCIAL_SECURITY.code(), EnterpriseType.SOCIALSECURITYPAYMENTAMOUNT.code());
        //社保缴纳比例
        encapsulation(enterpriseHistoryYearInfoList, enterpriseInfoDTO.getSocialSecurityPaymentProportion(), uuid, EnterpriseGroup.SOCIAL_SECURITY.code(), EnterpriseType.SOCIALSECURITYPAYMENTPROPORTION.code());
        //研发经费支出
        InnovativeInformationData iid = enterpriseInfoDTO.getInnovativeInformationData();
        //如果企业经费支出为空的话
        if(null == iid){
            enterpriseHistoryYearInfoDao.insertBatch(enterpriseHistoryYearInfoList);
        }else{
            encapsulation(enterpriseHistoryYearInfoList, iid.getData(), uuid, EnterpriseGroup.INNOVATE.code(), EnterpriseType.EXPENDITURE.code());
            enterpriseHistoryYearInfoDao.insertBatch(enterpriseHistoryYearInfoList);
            //企业注册主子表2信息
            InnovativeInformation innovativeInformation = new InnovativeInformation();
            innovativeInformation.setId(UUIDUtil.getUUID());
            innovativeInformation.setHighlyEducatedProportion(iid.getHighlyEducatedProportion());
            innovativeInformation.setEnterpriseId(uuid);
            innovativeInformation.setHightNewTechnology(iid.getHightNewTechnology());
            innovativeInformation.setHonorNumber(iid.getHonorNumber());
            innovativeInformation.setPatentsNumber(iid.getPatentsNumber());
            innovativeInformationDao.insert(innovativeInformation);
        }

        /**
         * 同步灵犀企业信息
         */
        sychEnterprise(enterpriseInfoDTO);

        //一旦注册成功，修改当前用户"是否认证企业"的状态为1
        User user = new User();
        user.setId(userId);
        user.setCertEnterprise(1);
        userBiz.updateSelectiveById(user);

        //此处需要维护用户和企业认证的关系
        LinkUserEnterprise linkUserEnterprise = new LinkUserEnterprise();
        linkUserEnterprise.setEnterpriseInfo(uuid);
        linkUserEnterprise.setUserId(userId);
        int k = linkUserEnterpriseDao.insert(linkUserEnterprise);
        if(k != 1){
            return ObjectRestResponse.failure(ObjectRestCode.SAVE_LINK_USER_ENTERPRISE_INFO_ERROR);
        }

        //当所有的保存和修改完成后，此处为了节省网络流量和内存空间，只返回企业认证id，返回给前台
        EnterpriseId enterpriseId = new EnterpriseId();
        enterpriseId.setId(uuid);
        return ObjectRestResponse.success(enterpriseId);
    }

    //封装参数
    private List<EnterpriseHistoryYearInfo> encapsulation(List<EnterpriseHistoryYearInfo> list, List<EnterpriseData> enterpriseDataList, String uuid, Integer group, Integer type){
        //如果信息没填的话
        if( null == enterpriseDataList || enterpriseDataList.isEmpty()){
            return list;
        }
        enterpriseDataList.forEach(enterpriseData -> {
            EnterpriseHistoryYearInfo enterpriseHistoryYearInfo = new EnterpriseHistoryYearInfo();
            enterpriseHistoryYearInfo.setId(UUIDUtil.getUUID());
            enterpriseHistoryYearInfo.setYears(enterpriseData.getYears());
            enterpriseHistoryYearInfo.setValue(enterpriseData.getValue());
            enterpriseHistoryYearInfo.setGroupIndo(group);
            enterpriseHistoryYearInfo.setType(type);
            enterpriseHistoryYearInfo.setEnterpriseId(uuid);
            list.add(enterpriseHistoryYearInfo);
        });
        return list;
    }

    @Override
    public ObjectRestResponse companyPortraits(String companyName, String creditCode, String legalPersonName, String idCard) {
        //查询工商信息表
        DemoBusiness demoBusiness = demoBusinessDao.queryByCreditCode(creditCode);
        DemoBusinessDTO demoBusinessDTO = demoBusinessConvert.toDto(demoBusiness);
        if(demoBusiness == null){
            return ObjectRestResponse.failure(ObjectRestCode.FIND_BUSINESS_INFO_ERROR);
        }
        DemoQualificationCertificate demoQualificationCertificate = new DemoQualificationCertificate();
        demoQualificationCertificate.setCompanyId(demoBusiness.getId());

        //查询资质证书表
        List<DemoQualificationCertificate> demoQualificationCertificateList = demoQualificationCertificateDao.queryAll(demoQualificationCertificate);
        List<DemoQualificationCertificateDTO> list = demoQualificationCertificateConvert.toDto(demoQualificationCertificateList);
        demoBusinessDTO.setDemoQualificationCertificateDTOS(list);
        return ObjectRestResponse.success(demoBusinessDTO);

    }

    /**
     * 校验企业信息
     */
    public static boolean checkEnterprise(EnterpriseInfoDTO enterpriseInfoDTO){
        Map<String,String> reqMap = new HashMap<>();
        reqMap.put("companyName",enterpriseInfoDTO.getName() );//单位名称
        reqMap.put("creditCode",enterpriseInfoDTO.getSocialCreditCode());//社会信用代码
        reqMap.put("legalPersonName", enterpriseInfoDTO.getLegalPersonName());//法人姓名
        reqMap.put("idCard",enterpriseInfoDTO.getLegalPersonIdCard());//法人身份证号
        String resultData = LingXiController.lingXiReq(JSON.toJSONString(reqMap), LingXiApiUrlConstant.checkCompanyInfo);
        JSONObject jsonObject = JSONObject.parseObject(resultData);
        int code =(int) jsonObject.get("code");
        if (code == 0){
            String data = jsonObject.getString("data");
            JSONObject jsonDataObject = JSONObject.parseObject(data);
            return jsonDataObject.getBoolean("status");
        }else {
            return false;
        }
    }

    /**
     * 同步企业信息
     */
    public void sychEnterprise(EnterpriseInfoDTO enterpriseInfoDTO){
        Map<String,Object> reqMap1 = new HashMap<>();
        reqMap1.put("companyName",enterpriseInfoDTO.getName());//单位名称
        reqMap1.put("creditCode",enterpriseInfoDTO.getSocialCreditCode());//社会信用代码
        reqMap1.put("legalPersonName",enterpriseInfoDTO.getLegalPersonName() );//法人姓名
        reqMap1.put("idCard",enterpriseInfoDTO.getLegalPersonIdCard());//法人身份证号
        reqMap1.put("site",enterpriseInfoDTO.getAddress());//省-市-区
        reqMap1.put("residence",enterpriseInfoDTO.getContactAddress());//住所
        reqMap1.put("industrySector",enterpriseInfoDTO.getIndustryFieldId());//行业领域(四级，使用逗号隔开)
        reqMap1.put("mainProducts",enterpriseInfoDTO.getProducts());//主营产品
        reqMap1.put("numberOfEmployees",enterpriseInfoDTO.getPeopleNumber());//员工总数



        reqMap1.put("yearRevenue",enterpriseDataOrList(enterpriseInfoDTO.getIncome()));//营业收入
        reqMap1.put("yearReturn",enterpriseDataOrList(enterpriseInfoDTO.getProfit()));//营业利润
        reqMap1.put("yearPay",enterpriseDataOrList(enterpriseInfoDTO.getTotalTax() ));//纳税总额
        reqMap1.put("yearIncurdebts",enterpriseDataOrList(enterpriseInfoDTO.getAssetLiabilityRatio()));//资产负债率
        reqMap1.put("socialSecurityLines",enterpriseDataOrList(enterpriseInfoDTO.getSocialSecurityPaymentAmount()));//社保缴纳额度
        reqMap1.put("socialSecurityPaymentProportion",enterpriseDataOrList(enterpriseInfoDTO.getSocialSecurityPaymentProportion()));//社保缴纳比例

        LxInnovativeInformationData lxInnovativeInformationData = new LxInnovativeInformationData();
        InnovativeInformationData innovativeInformationData = enterpriseInfoDTO.getInnovativeInformationData();
        if (innovativeInformationData != null) {
            lxInnovativeInformationData.setData(enterpriseDataOrList(innovativeInformationData.getData()));
            lxInnovativeInformationData.setBachelorDegreeAbove(String.valueOf(innovativeInformationData.getHighlyEducatedProportion()) + "%");
            lxInnovativeInformationData.setIsHighTechEnterPrise(innovativeInformationData.getHightNewTechnology());
            lxInnovativeInformationData.setPatentApplications(innovativeInformationData.getPatentsNumber());
            lxInnovativeInformationData.setPrizesOrHonorOfProvinceAbove(innovativeInformationData.getHonorNumber());
            reqMap1.put("expenditure", lxInnovativeInformationData);//研发经费支出
        }

        System.out.println("灵犀api，请求参数：" + JSON.toJSONString(reqMap1));
        String resultData1 = LingXiController.lingXiReq(JSON.toJSONString(reqMap1), LingXiApiUrlConstant.sendCompanyRegisterInfo);
        System.out.println("同步企业信息" + resultData1);
    }

    public List<String> enterpriseDataOrList(List<EnterpriseData> enterpriseData){
        List<String> list = new ArrayList<>();
        Map<String,String> stringStringMap = new HashMap<>();
        enterpriseData.forEach(e1 ->{
            stringStringMap.put("years", e1.getYears());
            stringStringMap.put("value", e1.getValue());
            list.add(JSON.toJSONString(stringStringMap));
        });
        return list;
    }
    public static void main(String[] args) {
        InnovativeInformationData innovativeInformationData = new InnovativeInformationData();
        innovativeInformationData.getHightNewTechnology();
        System.out.println(EnterpriseGroup.INNOVATE.code());
    }
}